const Moment = require('moment')
const express = require('express')
const router = express.Router()
const path = require('path')

const bodyParser = require('body-parser')
const expressValidator = require('express-validator')
const check = expressValidator.check
const validationResult = expressValidator.validationResult

const db = require('../db/db').db

// 创建application/x-www-form-urlencoded
router.use(bodyParser.urlencoded({
    extended: true
}))
// 创建application/json解析
router.use(bodyParser.json())

// 添加
router.get('/add', (req, res) => {
    let sqlStr = 'SELECT * FROM project;'
    let connection = db.connection()
    db.query(connection, sqlStr, (err, result) => {
        try {
            let projectList = result
            let tasktypeSqlStr = 'SELECT * FROM tasktype';
            let tConnection = db.connection()
            db.query(tConnection, tasktypeSqlStr, (terr, tresult) => {
                let tasktypeList = tresult
                res.render(path.join(path.dirname(__dirname), 'views', 'taskadd', 'index'), {
                    // detail: {
                    //     pro_id: 7,
                    //     type: 1,
                    //     duration: 1,
                    //     percent: 100,
                    //     createtime: '2020-04-30'
                    // },
                    title: req.query.source == 'fill' ? '补填任务' : '添加任务',
                    projectList: projectList,
                    tasktypeList: tasktypeList,
                    source: req.query.source,
                    err: req.query.err
                })
            })
            db.close(tConnection)
        } catch (err) {}
    })
    db.close(connection)
})

// 添加
router.post('/add', [
    check('project')
        .not()
        .isEmpty()
        .withMessage('请选择项目'),
    check('type')
        .not()
        .isEmpty()
        .withMessage('请选择任务类型'),
    check('con')
        .not()
        .isEmpty()
        .withMessage('请输入任务名称'),
    check('duration')
        .not()
        .isEmpty()
        .withMessage('请输入任务用时(小时)'),
    check('percent')
        .not()
        .isEmpty()
        .withMessage('请输入任务完成度')
], (req, res) => {
    let errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.redirect('/task/add?err=' + Object.values(errors.mapped())[0].msg)
    }
    let task = {
        project_id: req.body.project,
        type: req.body.type,
        con: req.body.con,
        duration: req.body.duration,
        percent: req.body.percent || 100,
        createtime: Moment().format('YYYY-MM-DD HH:mm:ss')
    }
    if (!!req.body.createtime) {
        task.createtime = req.body.createtime + ' 20:00:00'
    }
    // 插入数据
    let sqlStr = `
        INSERT INTO task(pro_id, type, con, duration, percent, createtime)
        VALUES ('${task.project_id}', '${task.type}', '${task.con}', '${task.duration}', '${task.percent}', '${task.createtime}')
    `
    let connection = db.connection()
    db.query(connection, sqlStr, task, (id) => {
        setTimeout(() => {
            if (!!req.body.source) {
                let targetPath = req.body.source
                if (targetPath == 'fill') {
                    targetPath = 'task/add?source=fill'
                }
                res.redirect('/' + targetPath)
            } else {
                res.redirect('/project/' + task.project_id)
            }
        }, 0)
    })
    db.close(connection)
    return false
})

// 保存
router.post('/save', [
    check('project')
        .not()
        .isEmpty()
        .withMessage('请选择项目'),
    check('type')
        .not()
        .isEmpty()
        .withMessage('请选择任务类型'),
    check('con')
        .not()
        .isEmpty()
        .withMessage('请输入任务名称'),
    check('duration')
        .not()
        .isEmpty()
        .withMessage('请输入任务用时(小时)'),
    check('percent')
        .not()
        .isEmpty()
        .withMessage('请输入任务完成度')
], (req, res) => {
    let errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.redirect('/task/add?err=' + Object.values(errors.mapped())[0].msg)
    }
    let task = {
        id: req.body.id,
        project_id: req.body.project,
        type: req.body.type,
        con: req.body.con,
        duration: req.body.duration,
        percent: req.body.percent,
        modtime: Moment().format('YYYY-MM-DD HH:mm:ss')
    }
    // 插入数据
    let sqlStr = `
        UPDATE task
        SET pro_id = ${task.project_id}, type = ${task.type}, con = '${task.con}', duration = ${task.duration}, percent = ${task.percent}, modtime= '${task.modtime}'
        WHERE id = ${task.id}
    `
    let connection = db.connection()
    db.query(connection, sqlStr, task, (id) => {
        setTimeout(() => {
            if (!!req.body.source) {
                res.redirect('/' + req.body.source)
            } else {
                res.redirect('/project/' + task.project_id)
            }
        }, 0)
    })
    db.close(connection)
    return false
})

// 删除
router.get('/delete', (req, res) => {
    let sqlStr = `
        DELETE FROM task WHERE id = '${req.query.taskId}'
    `
    let connection = db.connection()
    db.query(connection, sqlStr, () => {
        setTimeout(() => {
            if (!!req.query.source) {
                res.redirect('/' + req.query.source)
            } else {
                res.redirect('/project/' + req.query.proId)
            }
        }, 0)
    })
    db.close(connection)
    return false
})

// 修改
router.get('/:taskId', (req, res) => {
    let detailSqlStr = 'SELECT * FROM task WHERE id = ' + req.params.taskId
    let detailCon = db.connection()
    db.query(detailCon, detailSqlStr, (err, detail) => {
        let sqlStr = 'SELECT * FROM project;'
        let connection = db.connection()
        db.query(connection, sqlStr, (err, result) => {
            try {
                let projectList = result
                let tasktypeSqlStr = 'SELECT * FROM tasktype';
                let tConnection = db.connection()
                db.query(tConnection, tasktypeSqlStr, (terr, tresult) => {
                    let tasktypeList = tresult
                    res.render(path.join(path.dirname(__dirname), 'views', 'taskadd', 'index'), {
                        title: '修改任务',
                        projectList: projectList,
                        tasktypeList: tasktypeList,
                        detail: detail[0],
                        source: req.query.source,
                        err: req.query.err
                    })
                })
                db.close(tConnection)
            } catch (err) {}
        })
        db.close(connection)
    })
    db.close(detailCon)
})

module.exports = router